/**
 * Created by TomSean on 2017/3/14.
 */
var ManyParkManager = function ($parent) {
    this.$parent = $parent;
    this.sysUtils = new kendoUtils();
    this.init();
    return this;
}

ManyParkManager.prototype = {
    init : function() {
        var fieldArray = this.sysUtils.getBindFieldArray(this.$parent.find(".search-panel"));
        var functionArray = [
            {fName : "search_mpm", fs : this.findData},
            {fName : "reset_btn", fs : this.resetInfo}
        ];
        /* 虚拟卡/实体卡 */Utils.createDataDictDropDownList({div:this.$parent.find('#trafficPermitCategory'), parentModelKey:BASIS.TRAFFIC_PERMIT_CARD_TYPE.ROOT}, this);
        /* 卡状态[0.禁用 1.启用 2.挂失 3.注销] */Utils.createDataDictDropDownList({div:this.$parent.find('#trafficPermitStatus'), parentModelKey:BASIS.TRAFFIC_PERMIT_STATUS.ROOT}, this);
        this.bindBaseModels = new bindBaseModel(null, fieldArray, functionArray, null);
        this.sysUtils.bindDoucment(this.bindBaseModels, this.$parent, this);
        this.initTable();
        this.findData();
    },
    /*
     * 重置按钮
     */
    resetInfo:function(e){
        var that = $(e.target).data("that");
        that.sysUtils.setBindFieldNull(that.bindBaseModels.bindFieldArray);
    },
    checkMpm : function (id) {
        var _this = this;
        if (isEmpty(id)) {
            notification({title: "操作失败", message: "请选择需要修改的信息"}, "info");
            return;
        }
        JsonpAjax(baseApiPath + 'traffic_permit/update?id='+id, undefined, 'json', function(res) {
            _this.entity = res;
            _this.checkDiv = _this.sysUtils.openWindow(_this.checkDiv, {
                title : '卡检测',
                height : "680px",
                width : "900px",
                resizable : false,
                content : 'views/parkLotCenter/parkingLotInfo/traffic_permit_check.html'
            }, true);
        });
    },
    cancelMpm : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        _this.cancelDiv = _this.sysUtils.openWindow(_this.cancelDiv, {
            title : "注销卡",
            height : "580px",
            width : "650px",
            resizable : false,
            content : "views/parkLotCenter/parkingLotInfo/cancel_card.html",
            close:function(e){
                //关闭页面上的websocket连接
                clearInterval(cancelCard.timerRead);
                websocketFunManager.removeWebSocket(_this.$parent.parents("li").attr("data-code"));
                this.destroy();
                _this.findData();
            }
        }, true);
    },
    findData : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        var params = _this.sysUtils.getBindDocJson(_this.bindBaseModels.bindFieldArray);
        if(!isEmpty(params["startDate"])){
            params["startDate"] = params["startDate"].pattern("yyyy-MM-dd");
        }
        if(!isEmpty(params["endDate"])){
            params["endDate"] = params["endDate"].pattern("yyyy-MM-dd");
        }
        var url = baseApiPath + "traffic_permit/list";
        var grid = _this.$parent.find('#many_park_manager_data_list').data('kendoGrid');
        var data = {curdatetime:new Date().getTime(),jsonParam : JSON.stringify(params)};
        var dataSource = _this.sysUtils.getDataSource({url : url, data : data, dataType : 'odata'});
        grid.setDataSource(dataSource);
    },
    initTable : function() {
        var _this = this;
        var columns = [
            {
                width: 30,
                headerTemplate: '<input type="checkbox" gridId="many_park_manager_data_list" onclick="gridCheckAll(this)" />',
                template: '<input type="checkbox" value="${uniqueIdentifier}" name="traffic_permit_id" />'
            },
            {
                title : '通行证ID',
                field : 'uniqueIdentifier'
            },
            {
                title : '印刷卡号',
                template : '${null==data.printingNo ? "*虚拟卡无印刷卡号*" : data.printingNo}'
            },
            {
                width : 80,
                title : '车牌号',
                field : 'vehicleNo'
            },
            {
                title : '车主(编号)',
                template : '#: pbaOwnerInfoByOwnerCode.ownerName# (#: pbaOwnerInfoByOwnerCode.ownerCode#)'
            },
            {
                width : 70,
                title : '[主/副]',
                template:"#:Utils.getModelNameByParentKey(BASIS.TRAFFIC_PERMIT_SERVICE_TYPE.ROOT, masterCardFlag)#"
            },
            {
                width: 90,
                title : '卡种类',
                template:"#:Utils.getModelNameByParentKey(BASIS.TRAFFIC_PERMIT_CARD_TYPE.ROOT, trafficPermitCategory)#"
            },
            {
                width: 90,
                title : '通行证类型',
                field : 'crTrafficPermitType.trafficPermitName'
            },
            {
                width: 80,
                title : '车位(个)',
                field : 'spaceNumber'
            },
            {
                width: 90,
                title : '状态',
                template:"#:Utils.getModelNameByParentKey(BASIS.TRAFFIC_PERMIT_STATUS.ROOT, trafficPermitStatus)#"
            }
        ];
        _this.sysUtils.createGird(_this.$parent.find('#many_park_manager_data_list'),
            {
                selectable : 'single',
                autoSync : true,
                columnMenu : true,
                pageable : {input : true, numeric : false},
                columns : columns,

                change : function(e) {
                    var selected = $.map(this.select(), function(itm) {
                        return $(itm).find('input[type=checkbox]').val();
                    });
                    _this.selectRowId = selected[0];
                },
                dataBound : function() {
                    var $list = _this.$parent.find("#many_park_manager_data_list");
                    $list.find("tr").unbind("dblclick");
                    $list.find("tr").dblclick(function(e){
                        var grid = $list.data("kendoGrid");
                        var dataItem = grid.dataItem(grid.select());
                        //打开查看窗口
                        _this.isEdit = false;
                        _this.checkMpm(dataItem["uniqueIdentifier"]);
                    });
                }
            }
        );
    },
    updateMpm : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        _this.isEdit = true;
        if (!_this.selectRowId) {
            notification({title: "操作失败", message: "请选择需要修改的信息"}, "info");
            return;
        }
        JsonpAjax(baseApiPath + "traffic_permit/update?id="+_this.selectRowId, "", "json", function(res) {
            _this.entity = res;
            _this.openEditWindow("编辑通行证信息", true);
        });

    },
    newMpm : function(e) {
        var _this = this;
        _this.entity = undefined;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        _this.openEditWindow("新增包期通行证", false);
    },
    openEditWindow : function(title, isEdit) {
        var _this = this;
        _this.isEdit = isEdit;
        _this.editDiv =_this.sysUtils.openWindow(_this.editDiv, {
            title : title,
            height : "680px",
            width : "900px",
            resizable : false,
            content : "views/parkLotCenter/parkingLotInfo/many_park_manager_edit.html",
            close:function(e){
                //关闭页面上的websocket连接
                clearInterval(manyParkManagerEdit.timerRead);
                websocketFunManager.removeWebSocket(_this.$parent.parents("li").attr("data-code"));
                this.destroy();
            }
        }, true);
    }
}
var devInfos = new Array();
var ManyParkManagerEdit = function($parent) {
    this.$parent = $parent;
    this.ws = new webSocket(this.handlerMessage, this.openSuccess, this.onClose, manyParkManager.$parent);
    this.sysUtils = new kendoUtils();
    this.newNum = 0;
    this.init();
    return this;
}
ManyParkManagerEdit.prototype = {
    init : function() {
        var _this = this;
        this.entity = manyParkManager.entity;
        this.checkDeviceStatus = 0;
        this.readCardStatus = 0;
        var fieldArray = this.sysUtils.getBindFieldArray(this.$parent);
        var functionArray = [
            {fName : 'save_info', fs : this.saveInfo},
            {fName : 'save_and_continue', fs : function() { _this.save_and_continue=1; _this.saveInfo() }},
            {fName : 'save_and_subcard', fs : function() { _this.save_and_subcard=1; _this.saveInfo() }},
            {fName : 'check_device', fs : this.checkDevice},
            {fName : 'read_card', fs : this.readCard},
            {fName : 'cancel', fs : function() {$('#' + manyParkManager.editDiv).data('kendoWindow').close();}}
        ];
        this.bindBaseModels = new bindBaseModel(null, fieldArray, functionArray, null);
        this.sysUtils.bindDoucment(this.bindBaseModels, this.$parent, this);
        this.$parent.find('.search_owner_info').kendoAutoComplete({
            minLength : 1,
            filter: "contains",
            dataTextField : "ownerCode",
            template : "<span class='k-state-default'>#: ownerCode# <small style='font-size:12px;color:grey'>#: ownerName#</small></span>",
            dataSource : {
                type : "odata",
                serverFiltering: true,
                transport : {
                    read : {
                        url : baseApiPath + "owner_info/search"
                    }
                }
            },
            height : 400,
            select : function(e) {
                var dataItem = this.dataItem(e.item.index());
                var ownerCode = dataItem.ownerCode;
                _this.$parent.find('.search_owner_info').val(ownerCode);
                var ownerName = dataItem.ownerName;
                _this.$parent.find('.no-1-ownerName').html(ownerName);
                var ownerPhone = dataItem.ownerPhone;
                _this.$parent.find('.no-1-ownerPhone').html(ownerPhone);
                var ownerAddress = dataItem.ownerAddress;
                _this.$parent.find('.no-1-ownerAddress').html(ownerAddress);
                var organizationName = dataItem.organization.organizationName;
                _this.$parent.find('.no-1-organization').html(organizationName);
            }
        });
        var months = [{'text':'一个月', value:1},{'text':'两个月', value:2},{'text':'三个月', value:3},{'text':'四个月', value:4},{'text':'五个月', value:5},{'text':'六个月', value:6},{'text':'七个月', value:7},{'text':'八个月', value:8},{'text':'九个月', value:9},{'text':'十个月', value:10},{'text':'十一个月', value:11},{'text':'一年', value:12},{'text':'两年', value:24},{'text':'三年', value:36}];
        var selectMonthDropDownList = this.$parent.find('#selectMonth').kendoDropDownList({
            dataTextField: "text",
            dataValueField: "value",
            dataSource: months,
            change : function(e) {
                var valMonth = this.dataItem(e.item).value;
                _this.selectMonth = valMonth;
                _this.calMonth();
            }
        }).data('kendoDropDownList');
        selectMonthDropDownList.select(0);
        this.selectMonth = selectMonthDropDownList.dataItem(0).value;

        this.$parent.find('#search_master_card').kendoAutoComplete({
            minLength : 1,
            filter: "contains",
            dataTextField : "uniqueIdentifier",
            template : "<span class='k-state-default'>#: uniqueIdentifier#</span>",
            dataSource : {
                type : "odata",
                serverFiltering: true,
                transport : {
                    read : {
                        url : baseApiPath + "traffic_permit/search"
                    }
                }
            },
            height : 400,
            select : function(e) {
                var dataItem = this.dataItem(e.item.index());
                var type = dataItem.crTrafficPermitType.trafficPermitName;
                _this.$parent.find('#no-1-trafficType').html(type);
                var endTime = dataItem.endTime;
                _this.$parent.find('#no-1-endTime').html(endTime);
                var beginTime = dataItem.beginTime;
                _this.$parent.find('#no-1-beginTime').html(beginTime);
                var printingNo = dataItem.printingNo;
                _this.$parent.find('#no-1-printingNo').html(printingNo);
                var spaceNumber = dataItem.spaceNumber;
                _this.$parent.find('#no-1-spaceNumber').html(spaceNumber);
            }
        });
        /*  获取外接设备信息 */
        JsonpAjax(baseApiPath + "externalDevice/device_info/ic", undefined, 'json', function(res) {
            var list = res;
            if (devInfos.length > 0) {
                devInfos = new Array();
            }
            for (var i = 0; i < list.length; i++) {
                devInfos.push(list[i]);
            }
            var devices = _this.$parent.find('#device').kendoDropDownList({
                dataTextField : "deviceName",
                dataValueField : "deviceCode",
                dataSource : devInfos,
                change:function(e){
                    _this.checkDeviceStatus = 0;
                }
            }).data('kendoDropDownList');
            devices.select(0);
        }, true);
        this.$parent.find('#beginTime').kendoDatePicker({
            change : function() {
                _this.load$beginTime = this.value().pattern("yyyy-MM-dd");
                _this.loadPreferential();
                _this.calMonth();
            }
        });
        this.sysUtils.mvvmModel.set("beginTime", new Date());
        JsonpAjax(baseApiPath + 'traffic_permit_type/list/traffic', undefined, 'json', function(res) {
            var data = [];
            for (var i = 0; i < res.length; i++) {
                data.push(res[i]);
            }
            var ddl = _this.$parent.find('#trafficType').kendoDropDownList({
                dataTextField: "trafficPermitName",
                dataValueField: "id",
                dataSource: data,
                index:0,
                change : function() {
                    var dataItem = this.dataItem();
                    _this.$parent.find('#balance').val(dataItem.payMoney);
                    _this.calcMoney();
                    _this.loadTree(dataItem.id);
                }
            }).data('kendoDropDownList');
            ddl.select(0);
            _this.$parent.find('#balance').val(ddl.dataItem().payMoney);
            _this.loadTree(data[0].id);
            _this.calcMoney();
        }, true);
        // 加载信息
        this.loadInfo();

        // 获取优惠项目
        this.loadPreferential();

        // 计算截止时间
        this.calMonth();

    },
    loadTree:function (id) {
        var setting = {
            view: {
                showLine: true,
                selectedMulti: false,
                dblClickExpand: false,
                showIcon: false
            },
            data: {
                simpleData: {
                    enable:true,
                    idKey: "code",
                    pIdKey: "pid",
                    rootPId: ""
                }
            },
            async: {
                enable: true,
                type:"post",
                url: baseApiPath + "traffic_permit_type/channel/tree?id="+id,
            },
            callback : {
                onAsyncSuccess : function() {
                    var treeObj = $.fn.zTree.getZTreeObj("permit_tree");
                    treeObj.expandAll(true);
                }
            }
        };
        $.fn.zTree.init(this.$parent.find("#permit_tree"), setting);
    },
    calMonth : function() {
        var beginTime = new Date(this.$parent.find('#beginTime').val());
        var endTime = new Date(this.$parent.find('#beginTime').val());
        endTime.setMonth(beginTime.getMonth() + this.selectMonth);
        if (beginTime.getDate() != endTime.getDate()) {
            endTime.setDate(beginTime.getDate()-(endTime.getDate()));
            endTime.setMonth(endTime.getMonth()-1);
        } else {
            var beginDate = new Date(beginTime.getFullYear(), beginTime.getMonth()+1, 0);
            var endDate = new Date(endTime.getFullYear(), endTime.getMonth()+1, 0);
            if (beginDate.getDate() == beginTime.getDate() && endDate.getDate() != endTime.getDate()) {
                endTime.setDate(endDate.getDate());
            }
        }
        this.sysUtils.mvvmModel.set('endTime', endTime);
    },
    openSuccess : function(e) {
        console.log('与后台建立通信正常！');
    },
    onClose : function(e) {
        notification({title : "读卡设备异常", message : "连接断开，请检查设备、网络是否正常，再重新尝试读卡"}, 'info');
        clearInterval(manyParkManagerEdit.timerRead);
    },
    handlerMessage : function(e) {
        var data = JSON.parse(e.data);
        var $status = $('#readCardStatus');
        if (data.msgType == "REPLY" && data.replyType == "success") {
            if (!isEmpty(manyParkManagerEdit.readCardSerializeNumber) && manyParkManagerEdit.readCardSerializeNumber==data.serialNumber) {
                var result = JSON.parse(data.replayMsg);
                var phyid = result.phyid;//物理卡号
                var phytyp = result.phytyp; //物理卡类型
                var cardsno = result.cardsno;//逻辑卡号
                // 读卡成功时
                if (result.opstatus == 1) {
                    if (!isEmpty(manyParkManagerEdit.phyid) && manyParkManagerEdit.phyid != phyid) {
                        if (manyParkManagerEdit.noticeMessage == '当前卡与读卡信息不同，请换会读卡时的磁卡再操作') {
                            return;
                        }
                        manyParkManagerEdit.noticeMessage = '当前卡与读卡信息不同，请换会读卡时的磁卡再操作';
                        notification({title : '操作失败', message : '当前卡与读卡信息不同，请换会读卡时的磁卡再操作'}, 'info');
                        return;
                    }
                    if (cardsno != '0') {
                        if (manyParkManagerEdit.noticeMessage == '此卡已发行，请注销后再操作') {
                            return;
                        }
                        manyParkManagerEdit.noticeMessage = '此卡已发行，请注销后再操作';
                        notification({title : '操作失败', message : '此卡已发行，请注销后再操作'}, 'info');
                        return;
                    }
                    clearInterval(manyParkManagerEdit.timerRead);
                    manyParkManagerEdit.phyid = phyid;
                    manyParkManagerEdit.phytyp = phytyp;
                    $status.css({"color":"green"});
                    $status.html(phyid);
                    manyParkManagerEdit.readCardStatus = 1;
                    manyParkManagerEdit.$parent.find('#phyid').val(phyid);
                } else {
                    manyParkManagerEdit.phyid = undefined;
                    $status.css({"color":"red"});
                    $('#readCardStatus').html('读取卡失败');
                }
            } else if (!isEmpty(manyParkManagerEdit.checkDeviceSerializeNumber) && manyParkManagerEdit.checkDeviceSerializeNumber == data.serialNumber) {
                // 检测设备成功时
                manyParkManagerEdit.checkDeviceStatus = 1;
                manyParkManagerEdit.checkDeviceSerializeNumber = undefined;
                var $device = manyParkManagerEdit.$parent.find('#device').data('kendoDropDownList');
                var result = $device.dataItem($device.select());
                manyParkManagerEdit.devInfo = result;
                manyParkManagerEdit.$parent.find('#deviceStatus').html(result.deviceName + ' (' + result.deviceCode + ')');
                manyParkManagerEdit.$parent.find('#deviceStatus').css({'color':'green'});
                manyParkManagerEdit.timerRead = setInterval(function() {
                    manyParkManagerEdit.readCard();
                }, 1000);
            }
        } else {
            notification({title : '提示', message : '设备连接，请检测设备是否连接或重启设备后再试'}, 'info');
            clearInterval(manyParkManagerEdit.timerRead);
            return;
        }
    },
    readCard : function (e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        if (_this.checkDeviceStatus != 1) {
            notification({title : '操作失败', message : '请在读卡前测试设备是否连接成功'}, 'info')
            return;
        }
        _this.readCardStatus = 0;
        var $device = _this.$parent.find('#device').data('kendoDropDownList');
        var result = $device.dataItem($device.select());
        var jna = {};
        jna["reader"] = 0; //毒头？
        jna["sector"] = 15; //扇区号
        jna["deviceCacheInfo"] = result;
        var jnaStr = JSON.stringify(jna);
        manyParkManagerEdit.readCardSerializeNumber = _this.ws.sendMsgToWebSocket(jnaStr,"RC").serialNumber;
    },
    checkDevice : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        clearInterval(_this.timerRead);
        _this.checkDeviceStatus = 0;
        var $device = _this.$parent.find('#device').data('kendoDropDownList');
        var result = $device.dataItem($device.select());
        if (isEmpty(result) || isEmpty(result.deviceCode)) {
            _this.$parent.find('#deviceStatus').html('请先选择一个读卡器');
            _this.$parent.find('#deviceStatus').css({'color':'red'});
            return;
        }
        var jna = {"volume":1, "voicetext" : result.deviceName + "设备已连接", "lock":0, "deviceCacheInfo":result};
        _this.devInfo = undefined;
        var jnaStr = JSON.stringify(jna);
        _this.checkDeviceSerializeNumber = _this.ws.sendMsgToWebSocket(jnaStr,"VC").serialNumber;
        clearInterval(manyParkManagerEdit.timerRead);
    },
    getLogicNo : function() {
        var _this = this;
        var logicNo;
        JsonpAjax(baseApiPath + "traffic_permit/no/logic", undefined, 'json', function(res) {
            logicNo = res;
            _this.logicNo = logicNo;
            _this.$parent.find('#rationUniqueIdentifier').val(logicNo);
        }, true);
        return logicNo;
    },
    loadPreferential : function() {
        var _this = this;
        var dataT = {beginTime : this.load$beginTime, endTime : this.load$endTime};
        JsonpAjax(baseApiPath + "preferential/valid", dataT, "json", function(res) {
            var data = [];
            for (var i = 0; i < res.length; i++) {
                data.push(res[i]);
            }
            if (data.length < 1) {
                data.push({preferentialCode : -1, preferentialName:"暂无可用优惠"});
            }
            if (data.length > 0) {
                var dd = _this.$parent.find('#preferential').kendoDropDownList({
                    dataTextField: "preferentialName",
                    dataValueField: "preferentialCode",
                    dataSource : data,
                    change : function(e) {
                        var preferential = this.dataItem();
                        var type = preferential.preferentialType;
                        _this.calcType = type;
                        _this.calcValue = preferential.preferentialContent;
                        _this.calcMoney();
                    }
                }).data('kendoDropDownList');
                var preferential = dd.dataItem(dd.select());
                var type = preferential.preferentialType;
                _this.calcType = type;
                _this.calcValue = preferential.preferentialContent;
                _this.calcMoney();
            }
        });
    },
    calcMoney : function() {
        var _this = this;
        var type = _this.calcType;
        var val = _this.calcValue;
        var calc, sourceMoney, resultMoney;
        sourceMoney = _this.$parent.find('#balance').val();
        if (sourceMoney.charAt(sourceMoney.length-1) == '.') {
            sourceMoney = parseFloat(sourceMoney.substring(0, sourceMoney.length-1));
        }
        if (type == 0 /* 0抵用现金 */) {
            resultMoney = sourceMoney - val;
            if (resultMoney <= 0) {
                resultMoney = 0;
            }
            _this.$parent.find('#calc').html(' 优惠 '+val+'元&nbsp;');
        } else if (type == 1 /* 1折扣 */) {
            resultMoney = sourceMoney * val;
            _this.$parent.find('#calc').html(' 打 '+ (val*10)+'折');
        } else {
            resultMoney = sourceMoney;
            _this.$parent.find('#calc').html('');
        }
        resultMoney = resultMoney + '';
        if (resultMoney.indexOf('.') != -1) {
            /* 如果输入为小数，则保留最后2位 */
            var temp = resultMoney.substring(resultMoney.indexOf('.')+1);
            if (temp.length > 2) {
                temp = temp.substring(0, 2);
                resultMoney = resultMoney.substring(0, resultMoney.indexOf('.'));
                resultMoney = resultMoney + '.' + temp;
            }
        }
        _this.$parent.find('#sourceMoney').html(sourceMoney);
        _this.$parent.find('#resultMoney').html(resultMoney);
    },
    loadInfo : function() {
        var _this = this;
        if (manyParkManager.isEdit == true && manyParkManager.entity) {
            _this.entity = manyParkManager.entity;
            _this.entity.ownerCode = _this.entity.pbaOwnerInfoByOwnerCode.ownerCode;
            _this.entity.ownerName = _this.entity.pbaOwnerInfoByOwnerCode.ownerName;
            _this.entity.ownerPhone = _this.entity.pbaOwnerInfoByOwnerCode.ownerPhone;
            _this.entity.ownerAddress = _this.entity.pbaOwnerInfoByOwnerCode.ownerAddress;
            _this.entity.organizationName = _this.entity.pbaOwnerInfoByOwnerCode.organization.organizationName;
            _this.sysUtils.setBindFieldValue(_this.entity);
            _this.entity = undefined;
            manyParkManager.entity = undefined;

        }
        _this.$parent.find("#new_subcar_owner_code").kendoAutoComplete({
            minLength : 1,
            filter: "contains",
            dataTextField : "ownerCode",
            template : "<span class='k-state-default'>#: ownerCode# <small style='font-size:12px;color:grey'>#: ownerName#</small></span>",
            dataSource : {
                type : "odata",
                serverFiltering: true,
                transport : {
                    read : {
                        url : baseApiPath + "owner_info/search"
                    }
                }
            },
            height : 400
        });
        var logicNo = this.getLogicNo();
        Utils.createDataDictDropDownList({div:this.$parent.find('#category'),
            change:function(e) {
                var dataItem = this.dataItem(e.item);
                if (dataItem.modelName == "虚拟卡") {
                    _this.$parent.find('#readCard').hide(200);
                    _this.$parent.find('#printingNoParam').hide(200);
                    _this.$parent.find('#trafficEntityCardParam').hide(200);
                    _this.$parent.find('#deviceStatus').parents('h3').hide(200);
                    _this.$parent.find('#readCardStatus').parents('h3').hide(200);
                } else {
                    _this.$parent.find('#readCard').show(200);
                    _this.$parent.find('#printingNoParam').show(200);
                    _this.$parent.find('#trafficEntityCardParam').show(200);
                    _this.$parent.find('#deviceStatus').parents('h3').show(200);
                    _this.$parent.find('#readCardStatus').parents('h3').show(200);
                }
            },
            parentModelKey:BASIS.TRAFFIC_PERMIT_CARD_TYPE.ROOT, select:Utils.getModelValueByModelKey(BASIS.TRAFFIC_PERMIT_CARD_TYPE.ENTITY)}, this);
    },
    saveInfo : function (e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        if (_this.$parent.find('#category').val() == 1) {
            if (_this.checkDeviceStatus != 1) {
                notification({title : '操作失败', message : '请先连接设备'}, 'info');
                return;
            }
            if (_this.readCardStatus != 1) {
                notification({title : '操作失败', message : '请先读取卡信息'}, 'info');
                return;
            }
            var printNo = _this.$parent.find('#printingNo').val();
            if (printNo == '') {
                notification({title : '警告', message : '印刷号不能为空'}, 'info');
                return;
            }
        }
        if (validityForm(_this.$parent)) {
            var entity = _this.sysUtils.getBindDocJson();
            entity['crTrafficPermitType.id'] = _this.$parent.find('#trafficType').val();
            if (!isEmpty(entity['ownerCode'])) {
                entity['pbaOwnerInfoByOwnerCode.ownerCode'] = entity['ownerCode'];
                entity['ownerCode'] = undefined;
            }
            var physicNumber = _this.$parent.find('#phyid').val();
            entity['physicNumber'] = physicNumber;
            entity['phytyp'] = _this.phytyp;
            var rationUniqueIdentifier = _this.$parent.find('#rationUniqueIdentifier').val();
            entity['rationUniqueIdentifier'] = rationUniqueIdentifier;
            var mcf = 0;
            _this.$parent.find('[name="masterCardFlag"]').each(function(inx, itm) {
                if (itm.checked) mcf = itm.value;
            });
            entity['masterCardFlag'] = mcf;
            if (mcf == 1) {
                var masterId = _this.$parent.find('#search_master_card').val();
                entity['parent'] = masterId;
            }
            entity['devInfo'] = JSON.stringify(_this.devInfo);
            manyParkManagerEdit.phyid = undefined;
            JsonpAjax(baseApiPath + "traffic_permit/update/save", JSON.stringify(entity), 'json', function(res) {
                //保存成功后 将读卡状态改为未读 防止下次重复点击保存
                _this.readCardStatus = 0;
                if (isEmpty(_this.save_and_subcard) && isEmpty(_this.save_and_continue)) {
                    $('#'+manyParkManager.editDiv).data('kendoWindow').close();
                } else if (!isEmpty(_this.save_and_subcard) && _this.save_and_subcard==1) {
                    var v = 0;
                    _this.$parent.find('[name="masterCardFlag"]').each(function(inx, itm) {
                        if (itm.checked) {
                            v = itm.value;
                        }
                    });
                    if (v == 0) {
                        _this.$parent.find('#search_master_card').val(res.uniqueIdentifier);
                        _this.$parent.find('#no-1-trafficType').html(res.crTrafficPermitType.trafficPermitName);
                        _this.$parent.find('#no-1-printingNo').html(res.printingNo);
                        _this.$parent.find('#no-1-spaceNumber').html(res.spaceNumber);
                        _this.$parent.find('#no-1-beginTime').html(res.beginTime);
                        _this.$parent.find('#no-1-endTime').html(res.endTime);
                    }
                    _this.$parent.find('[name="masterCardFlag"]').each(function(inx, itm) {
                        if (itm.value == "1") {
                            itm.checked = true;
                            $(itm).parent().click();
                        }
                    });
                    _this.$parent.find('.step-head[data-no="2"]').click();
                    _this.$parent.find('#need_commit_table #phyid').val('');
                    _this.$parent.find('#need_commit_table #vehicleNo').val('');
                    _this.$parent.find('#need_commit_table #printingNo').val('');
                    _this.$parent.find('#need_commit_table #rationUniqueIdentifier').val('');
                    _this.$parent.find('#balance').val(0);
                    _this.save_and_subcard = undefined;
                    _this.calcMoney();
                    _this.getLogicNo();
                    _this.timerRead = setInterval(function() {
                        manyParkManagerEdit.readCard();
                    }, 1000);
                } else if (!isEmpty(_this.save_and_continue) && _this.save_and_continue==1) {
                    _this.$parent.find('[name="masterCardFlag"]').each(function(inx, itm) {
                        if (itm.value == "0") {
                            itm.checked = true;
                            $(itm).parent().click();
                        }
                    });
                    _this.$parent.find('.step-head[data-no="2"]').click();

                    _this.$parent.find('#need_commit_table #phyid').val('');
                    _this.$parent.find('#need_commit_table #vehicleNo').val('');
                    _this.$parent.find('#need_commit_table #printingNo').val('');
                    _this.$parent.find('#need_commit_table #spaceNumber').val('');
                    _this.$parent.find('#need_commit_table #rationUniqueIdentifier').val('');

                    _this.$parent.find('#search_master_card').val('');
                    _this.$parent.find('#no-1-trafficType').html('');
                    _this.$parent.find('#no-1-printingNo').html('');
                    _this.$parent.find('#no-1-spaceNumber').html('');
                    _this.$parent.find('#no-1-beginTime').html('');
                    _this.$parent.find('#no-1-endTime').html('');

                    _this.save_and_continue = undefined;
                    _this.calcMoney();
                    _this.getLogicNo();
                    _this.timerRead = setInterval(function() {
                        manyParkManagerEdit.readCard();
                    }, 1000);
                } else {
                    $('#'+manyParkManager.editDiv).data('kendoWindow').close();
                }
                manyParkManager.findData();
            });
        }

    },
    confirmOwnerCode : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        //var tbody = _this.$parent.find('#sub_card_list tbody')[0];
        var val = _this.$parent.find('#new_subcar_owner_code').val();
        JsonpAjax(baseApiPath + 'owner_info/' + val, '', 'json', function (res) {
            var info = res[0];
            var vehicles = res[1];
            _this.cacheSubCardInfo = info;
            _this.cacheSubCardVehicles = vehicles;
            var select = _this.$parent.find('select#new_subcar_vehicles');
            select = select[0];
            if (vehicles.length > 0) {
                $(select).find('option').remove();
                for (var i = 0; i < vehicles.length; i++) {
                    var option = document.createElement("option");
                    option.value = vehicles[i].id;
                    option.setAttribute("data-name", info.ownerName);
                    option.setAttribute("data-phone", info.ownerPhone);
                    option.innerHTML = vehicles[i].vehicleNo;
                    select.appendChild(option);
                }
            } else {
                notification({title : "警告", message : "此人名下没有任何车辆记录"}, 'info')
            }
        });
    }
}


/* =============           注销卡         ==================  */
/*===========================================================*/
var CancelCard = function($parent) {
    this.$parent = $parent;
    this.sysUtils = new kendoUtils();
    this.init();
    return this;
}
CancelCard.prototype = {
    init : function() {
        var _this = this;
        this.ws = new webSocket(this.handlerMessage, this.openSuccess, this.onClose, manyParkManager.$parent);
        /*  获取外接设备信息 */
        JsonpAjax(baseApiPath + "externalDevice/device_info/ic", undefined, 'json', function(res) {
            var list = res;
            if (devInfos.length > 0) {
                devInfos = new Array();
            }
            for (var i = 0; i < list.length; i++) {
                devInfos.push(list[i]);
            }
            var devices = _this.$parent.find('#device').kendoDropDownList({
                dataTextField : "deviceName",
                dataValueField : "deviceCode",
                dataSource : devInfos,
                select:function(e){
                    _this.checkDeviceStatus = 0;
                }
            }).data('kendoDropDownList');
            devices.select(0);
        }, true);

        var fieldArray = _this.sysUtils.getBindFieldArray(_this.$parent);
        var functionArray = [
            {fName : "check_device", fs : _this.checkDevice},
            {fName : "read_card", fs : _this.readCard},
            {fName : "cancel_card", fs : _this.cancelCard},
            {fName : "close_cancel", fs : function() { $('#' + manyParkManager.cancelDiv).data('kendoWindow').close(); }}
        ];
        _this.$parent.find('[name="model_function"]').click(function(e) {
            if ($(this).is(":checked")) {
                if ( $(this).val() == "1" ) {
                    _this.$parent.find('#auto-cancel').fadeOut('fast');
                    _this.$parent.find('#manual-cancel').fadeIn('fast');
                } else {
                    _this.$parent.find('#auto-cancel').fadeIn('fast');
                    _this.$parent.find('#manual-cancel').fadeOut('fast');
                }
                if (_this.checkDeviceStatus == 1) {
                    clearInterval(cancelCard.timerRead);
                    cancelCard.timerRead = setInterval(function() {
                        cancelCard.readCard();
                    }, 1000);
                }
            }
        });
        _this.bindBaseModels = new bindBaseModel(null, fieldArray, functionArray, null);
        _this.sysUtils.bindDoucment(_this.bindBaseModels, _this.$parent, _this);

    },
    onClose : function() {
        console.log('连接关闭');
        clearInterval(cancelCard.timerRead);
    },
    openSuccess : function() {
        console.log('连接打开');
    },
    readCard : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        if (_this.checkDeviceStatus != 1) {
            notification({title : '操作失败', message : '请在读卡前测试设备是否连接成功'}, 'info');
            return;
        }
        _this.readCardStatus = 0;
        var $device = _this.$parent.find('#device').data('kendoDropDownList');
        var result = $device.dataItem($device.select());
        var jna = {};
        jna["reader"] = 0; //毒头？
        jna["sector"] = 15; //扇区号
        jna["deviceCacheInfo"] = result;
        var jnaStr = JSON.stringify(jna);
        cancelCard.readCardSerializeNumber = _this.ws.sendMsgToWebSocket(jnaStr,"RC").serialNumber;
    },
    checkDevice : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        clearInterval(_this.timerRead);
        _this.checkDeviceStatus = 0;
        var $device = _this.$parent.find('#device').data('kendoDropDownList');
        var result = $device.dataItem($device.select());
        if (isEmpty(result) || isEmpty(result.deviceCode)) {
            _this.$parent.find('#deviceStatus').html('请先选择一个读卡器');
            _this.$parent.find('#deviceStatus').css({'color':'red'});
            return;
        }
        var jna = {"volume":1, "voicetext":result.deviceName+"设备已连接", "lock":0, "deviceCacheInfo":result};
        var jnaStr = JSON.stringify(jna);
        _this.devInfo = undefined;
        _this.noInfoCard = undefined;
        _this.checkDeviceSerializeNumber = _this.ws.sendMsgToWebSocket(jnaStr,"VC").serialNumber;
    },
    handlerMessage : function(e) {
        var data = JSON.parse(e.data);
        var $status = $('#readCardStatus');
        if (data.msgType == "REPLY" && data.replyType == "success") {
            if (!isEmpty(cancelCard.readCardSerializeNumber) && cancelCard.readCardSerializeNumber==data.serialNumber) {
                var result = JSON.parse(data.replayMsg);
                // 读卡成功时
                if (result.opstatus == 1) {
                    clearInterval(cancelCard.timerRead);
                    $status.css({"color":"green"});
                    cancelCard.$parent.find('#readCardStatus').html('检测到卡');
                    cancelCard.$parent.find('#cardno').html(result.cardsno);
                    if (result.cardsno == 0) {
                        cancelCard.$parent.find('#vehicleNo').html('此卡未发行');
                        cancelCard.$parent.find('#ownerName').html('此卡未发行');
                        cancelCard.$parent.find('#cardType').html('此卡未发行');
                        cancelCard.noInfoCard = result.phyid;
                        if (cancelCard.$parent.find('[name="model_function"]:checked').val() == "0") {
                            logInfoToCancelMpm("此卡未发行，注销失败", 'error');
                        }
                        cancelCard.timerRead = setInterval(function() {
                            cancelCard.readCard();
                        }, 1000);
                        return;
                    }
                    cancelCard.$parent.find('#vehicleNo').html("正在获取./..");
                    cancelCard.$parent.find('#ownerName').html("正在获取./..");
                    cancelCard.$parent.find('#cardType').html("正在获取./..");
                    var param = {'cardno' : result.cardsno, 'cardtype' : result.cardtype};
                    JsonpAjax(baseApiPath + "traffic_permit/info/owner_type", JSON.stringify(param), 'json', function(res) {
                        var card = res[0];
                        if (card) {
                            cancelCard.$parent.find('#vehicleNo').html(card.vehicleNo);
                            cancelCard.$parent.find('#ownerName').html(card.pbaOwnerInfoByOwnerCode.ownerName);
                            cancelCard.$parent.find('#cardType').html(card.crTrafficPermitType.trafficPermitName);
                        }
                        if (cancelCard.$parent.find('[name="model_function"]:checked').val() == "0") {
                            logInfoToCancelMpm("正在注销 ./.. {"+result.cardsno + "}", 'waring');
                            cancelCard.cancelCard();
                        }
                    });
                    cancelCard.phyid = result.phyid;
                    cancelCard.phytyp = result.phytyp;
                } else {
                    cancelCard.phyid = undefined;
                    cancelCard.phytyp = undefined;
                    cancelCard.noInfoCard = undefined;
                    cancelCard.$parent.find('#vehicleNo').html('自动获取');
                    cancelCard.$parent.find('#ownerName').html('自动获取');
                    cancelCard.$parent.find('#cardType').html('自动获取');
                    $status.css({"color":"red"});
                    cancelCard.$parent.find('#readCardStatus').html('未检测到卡');
                    if (cancelCard.$parent.find('[name="model_function"]:checked').val() == "0") {
                        logInfoToCancelMpm("未检测到卡", 'waring');
                    }
                }
            } else if (!isEmpty(cancelCard.checkDeviceSerializeNumber) && cancelCard.checkDeviceSerializeNumber == data.serialNumber) {
                // 检测设备成功时
                cancelCard.checkDeviceStatus = 1;
                cancelCard.checkDeviceSerializeNumber = undefined;
                var $device = cancelCard.$parent.find('#device').data('kendoDropDownList');
                var result = $device.dataItem($device.select());
                cancelCard.devInfo = result;
                cancelCard.$parent.find('#readCardStatus').css({'color':'green'});
                cancelCard.$parent.find('#readCardStatus').html(result.deviceName + ' 正常');
                cancelCard.timerRead = setInterval(function() {
                    cancelCard.readCard();
                }, 1000);
            }
        } else {
            notification({title : '提示', message : '设备异常，请检测设备是否连接或重启设备后再试'}, 'info');
            clearInterval(cancelCard.timerRead);
            return;
        }
    },
    cancelCard : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        if (_this.checkDeviceStatus != 1) {
            notification({title : '操作失败', message : '请先将卡放置到设备上'}, 'info');
            return;
        }
        var $device = _this.$parent.find('#device').data('kendoDropDownList');
        var result = $device.dataItem($device.select());
        if (isEmpty(result) || isEmpty(result.deviceCode)) {
            notification({title : '提示', message : '请先选择一个读卡设备'}, 'info');
            return;
        }
        if (_this.$parent.find('#cardno').html() == "0") {
            if (cancelCard.$parent.find('[name="model_function"]:checked').val() == "0") {
                logInfoToCancelMpm("此卡未发行，注销失败", 'error');
            } else {
                notification({title : '操作失败', message : '此卡未发行，注销失败'}, 'info');
            }
            return;
        }
        var dataT = {'devInfo':JSON.stringify(result), 'phyid':_this.phyid, 'phytyp':_this.phytyp, 'id':_this.$parent.find('#cardno').html()};
        JsonpAjax(baseApiPath + 'traffic_permit/cancel', dataT, 'json', function(res) {
            cancelCard.timerRead = setInterval(function() {
                cancelCard.readCard();
            }, 1000);
            if (cancelCard.$parent.find('[name="model_function"]:checked').val() == "0") {
                logInfoToCancelMpm("注销成功", 'success');
            }
        });
    }
}

function deleteManyParkManagerEditTablesParkLotSpace(id, tableId) {
    $('tr[data-id='+id+']').remove();
    var $list = manyParkManagerEdit.$parent.find('#' + tableId);
    var $thead = $list.find('thead');
    var tbody = $list.find('tbody');
    if ($(tbody).find("tr").length < 1) {
        var tr = document.createElement("tr");
        tr.setAttribute("data-id", "none-data");
        var td_code = document.createElement("td");
        td_code.colSpan = $thead.find('th').length;
        td_code.style.textAlign = "center";
        td_code.innerHTML = "<span style='color:#ccc'>暂无数据</span>";
        tr.appendChild(td_code)
        tbody[0].appendChild(tr);
    }
}

/**
 * 在控制台打印信息
 * @param msg 消息
 * @param typ info | success | error | waring
 */
function logInfoToCancelMpm(msg, typ) {
    if (window.logInfoToCancelMsg == msg) {
        return;
    }
    window.logInfoToCancelMsg = msg;
    msg = "[" + new Date().pattern("yyyy-MM-dd HH:mm:ss") + "]&nbsp;&nbsp;" + msg + "<br>";
    if (typ == 'info') {
        msg = '<span style="color:cornflowerblue">' + msg;
    } else if (typ == 'success') {
        msg = '<span style="color:forestgreen">' + msg;
    } else if (typ == 'error') {
        msg = '<span style="color:indianred">' + msg;
    } else if (typ == 'waring') {
        msg = '<span style="color:#a36d03">' + msg;
    } else {
        msg = '<span style="color:black">' + msg;
    }
    msg += '</span>';
    cancelCard.$parent.find('#opa-info').prepend(msg);
}



var TrafficPermitCheck = function ($parent) {
    this.$parent = $parent;
    this.sysUtils = new kendoUtils();
    this.init();
    return this;
}
TrafficPermitCheck.prototype = {
    init : function () {
        var fieldArray = this.sysUtils.getBindFieldArray(this.$parent);
        var functionArray = [
            {fName : 'cancel', fs : function () { $('#'+manyParkManager.checkDiv).data('kendoWindow').close(); }}
        ];
        this.models = new bindBaseModel(null, fieldArray, functionArray, null);
        this.sysUtils.bindDoucment(this.models, this.$parent, this);
        this.checkTrafficPermit();
    },
    checkTrafficPermit : function () {
        var _this = this;
        this.sysUtils.setBindFieldValue(manyParkManager.entity);
        this.$parent.find('#category').val(Utils.getModelNameByParentKey(BASIS.TRAFFIC_PERMIT_CARD_TYPE.ROOT, manyParkManager.entity.trafficPermitCategory));
        this.$parent.find('#trafficType').val(manyParkManager.entity.crTrafficPermitType.trafficPermitName);

        this.$parent.find('.search_owner_info').val( manyParkManager.entity.pbaOwnerInfoByOwnerCode.ownerCode);
        this.$parent.find('.no-1-ownerName').html( manyParkManager.entity.pbaOwnerInfoByOwnerCode.ownerName);
        this.$parent.find('.no-1-organization').html( manyParkManager.entity.pbaOwnerInfoByOwnerCode.organization.organizationName);
        this.$parent.find('.no-1-ownerPhone').html( manyParkManager.entity.pbaOwnerInfoByOwnerCode.ownerPhone);
        this.$parent.find('.no-1-ownerAddress').html( manyParkManager.entity.pbaOwnerInfoByOwnerCode.ownerAddress);

        if (manyParkManager.entity.masterCardFlag == 1) {
            $('#master_card_ext_info').fadeIn('slow');
            JsonpAjax(baseApiPath + 'traffic_permit/' + manyParkManager.entity.parent, undefined, 'json', function(res) {
                _this.$parent.find('#master_card_uniqueIdentifier').val(res.uniqueIdentifier);
                _this.$parent.find('#master_card_category').val(Utils.getModelNameByParentKey(BASIS.TRAFFIC_PERMIT_CARD_TYPE.ROOT, res.trafficPermitCategory));
                _this.$parent.find('#master_card_type').val(res.crTrafficPermitType.trafficPermitName);
                _this.$parent.find('#master_card_ownerName').val(res.pbaOwnerInfoByOwnerCode.ownerName);
                _this.$parent.find('#master_card_vehicleNo').val(res.vehicleNo);
                _this.$parent.find('#master_card_ownerPhone').val(res.pbaOwnerInfoByOwnerCode.ownerPhone);
                _this.$parent.find('#master_card_printingNo').val(res.printingNo);
                $('#master_card_ext_info')[0].style.top = '0px';
            }, true);
        } else {
            this.$parent.find('#master_card_ext_info').hide();
            this.$parent.find('#master_card_ext_info')[0].style.top = '-235px';
        }
        manyParkManager.entity = undefined;
    }
}




























